/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import java.util.List;
import POJO.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Master
 */
public class DAO_TaiKhoan {
    public List<POJO_TaiKhoan> LoadList() throws SQLException{
        DataProvider data = new DataProvider();
        data.Open();
        
        List<POJO_TaiKhoan> list = new ArrayList<>();
        String query = "Select * from tai_khoan";
        ResultSet rs = data.ExecuteQuery(query);
        
        while(rs.next()){
            POJO_TaiKhoan taiKhoan = new POJO_TaiKhoan();
            
            taiKhoan.setMatkhau(rs.getString("MatKhau"));
            taiKhoan.setNgaytao(rs.getString("NgayTao"));
            taiKhoan.setManv(rs.getString("MaNV"));
            taiKhoan.setQuyen(rs.getString("Quyen"));
            taiKhoan.setTentk(rs.getString("TenTK"));
            
            list.add(taiKhoan);
        }
        return list;
    }
    
    public void Insert(POJO_TaiKhoan taiKhoan){
        DataProvider data = new DataProvider();
        data.Open();
        
        String password = data.MD5(taiKhoan.getMatkhau() + taiKhoan.getNgaytao());
        String query = String.format("INSERT INTO `tai_khoan`(`TenTK`, `MatKhau`, `MaNV`, `Quyen`, `NgayTao`) VALUES ('%s','%s','%s','%s','%s')", taiKhoan.getTentk(), password, taiKhoan.getManv(), taiKhoan.getQuyen(), taiKhoan.getNgaytao());
        
        data.ExeCuteUpdate(query);
    } 
    
    public void Update(POJO_TaiKhoan taiKhoan){
        DataProvider data = new DataProvider();
        data.Open();
        
        String password = data.MD5(taiKhoan.getMatkhau() + taiKhoan.getNgaytao());
        String query = String.format("UPDATE `tai_khoan` SET `TenTK`=TenTK,`MatKhau`= MatKhau,`MaNV`=MaNV,`Quyen`='%s',`NgayTao`=NgayTao WHERE TenTK = '%s'", taiKhoan.getQuyen(), taiKhoan.getTentk());
        
        data.ExeCuteUpdate(query);
    }
    
    public void Delete(POJO_TaiKhoan taiKhoan){
        DataProvider data = new DataProvider();
        data.Open();
        
        String query = String.format("DELETE FROM `tai_khoan` WHERE tentk = '%s'", taiKhoan.getTentk());
        
        data.ExeCuteUpdate(query);
    }
}
